#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

using pii = pair<int, int>;
using minheap = priority_queue<pii, vector<pii>, greater<pii>>;

#define x first
#define y second

const int N = 2e5 + 5;
const int M = 1e9 + 7;

int t, n, k;


struct Edge {
    int to, next;
} e[N << 1];

int head[N], idx = 1, in[N];

void add_edge(int u, int v) {
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx++;
}

void clear_graph() {
    // memset(head, -1, sizeof(head));
    // memset(e, 0, sizeof(e));
    // memset(in, 0, sizeof(in));

    for (int i = 1; i <= n; i++) head[i] = -1, e[i] = {0, 0}, in[i] = 0;

    idx = 1;
}

int bfs() {
    minheap p;
    for (int i = 1; i <= n; i++)
        if (!in[i])
            p.push({ 1, i });

    int rounds = 1, cnt = 0;
    while (!p.empty()) {
        auto t = p.top();
        p.pop();

        int u = t.y;
        cnt++, rounds = max(rounds, t.x);

        for (int i = head[u]; ~i; i = e[i].next) {
            int j = e[i].to;
            in[j]--;
            if (in[j] == 0) {
                if (j > u) p.push({ t.x, j });
                else p.push({ t.x + 1, j });
            }
        }
    }

    if (cnt == n) return rounds;
    else return -1;
}

int main() {
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    ios::sync_with_stdio(false), cin.tie(0);
    cin >> t;
    while (t--) {
        cin >> n;
        clear_graph();
        for (int i = 1; i <= n; i++) {
            cin >> k;
            int j;
            while (k--) {
                cin >> j;
                add_edge(j, i);
                in[i]++;
            }
        }

        cout << bfs() << endl;
    }
    return 0;
}